package com.arpa.wms.handler;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.wms.domain.dto.AuthDto;
import com.arpa.wms.domain.entity.Shop;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.gson.*;
import com.google.gson.internal.LinkedTreeMap;
import com.kuaishou.merchant.open.api.KsMerchantApiException;
import com.kuaishou.merchant.open.api.client.oauth.OauthAccessTokenKsClient;
import com.kuaishou.merchant.open.api.response.oauth.KsAccessTokenResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static com.arpa.wms.handler.AbstractTokenManagerHandler.KS_TOKEN_MANAGER;


/**
 * 快手token处理
 *
 * @author lxl
 * @since 2021-09-16
 */
@Log4j2
@Component(KS_TOKEN_MANAGER)
public class KsTokenBasicHandler extends AbstractTokenManagerHandler {

    String appKey = "ks667095696752023147";
    String appSecret = "kdkHhA8_Re9lq5zeKASumg";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refreshToken(Shop shop) {
        try {
            log.info("快手token刷新处理。{}", JSONUtil.toJsonStr(shop));
            OauthAccessTokenKsClient oauthAccessTokenKsClient = new OauthAccessTokenKsClient(appKey, appSecret);
            KsAccessTokenResponse response = oauthAccessTokenKsClient.refreshAccessToken(shop.getRefreshToken());
            log.info("快手token刷新处理，结果：{}",response);
            if(response.getResult() == 1){
                String accessToken = response.getAccessToken();
                String refreshToken = response.getRefreshToken();
                int expiresIn = (int) response.getExpiresIn();
                DateTime gmtTokenExp = DateUtil.offset(DateUtil.date(), DateField.SECOND, expiresIn);
                if (!StrUtil.equals(accessToken, shop.getAccessToken())) {
                    log.info("快手token刷新处理，更新token，{}",accessToken);
                    shop.setAccessToken(accessToken);
                    shop.setGmtTokenExp(gmtTokenExp);
                    shop.setRefreshToken(refreshToken);
                    Set<String> carrierCodes = shopMapper.getCarrierCode(shop.getCode());

                    log.info("快手token刷新处理，更新token，清除承运商缓存,{}",JSONUtil.toJsonStr(carrierCodes));
                    carrierCache.flushCaches(carrierCodes);
                    log.info("快手token刷新处理，更新token，清除店铺缓存,{}",shop.getCode());
                    shopCache.flushCaches(shop.getCode(),shop.getShipmentCode());
                    shopMapper.updateById(shop);
                    log.info("快手token刷新处理，更新token，更新店铺TOKEN,{}",shop.getCode());
                    shopMapper.updateCarrierToken(accessToken, shop.getCode());
                    log.info("快手token刷新处理，更新token，更新承运商TOKEN,{}",shop.getCode());
                }
            }
        }catch (KsMerchantApiException e) {
        e.printStackTrace();
        }
    }

    /**
     * 获取token
     *
     * @param dto 授权信息
     * @author liuxr
     * @date 2021/10/25 17:19
     */
    @Override
    public void getToken(AuthDto dto) {

        try {
            //不指定服务器地址，服务器地址默认为线上
            OauthAccessTokenKsClient oauthAccessTokenKsClient = new OauthAccessTokenKsClient(appKey, appSecret);
            KsAccessTokenResponse response = oauthAccessTokenKsClient.getAccessToken(dto.getCode());
            if (response.getResult() != 1) {
                String message = response.getErrorMsg();
                log.error(message);
                throw new ServiceException(message);
            }
//            shop.setAccessToken(accessToken);
//            shop.setRefreshToken(refreshToken);
//            shop.setGmtTokenExp(gmtTokenExp);
//            shopMapper.updateById(shop);



        } catch (Exception e) {
            log.error("电子面单-快手-获得access token异常",e);
        }
    }
}


